<?php 

namespace app\api\controller;

class Base extends Common{
	
	
	/**
	* @api {post} /Base/upload 01、图片上传
	* @apiGroup Base
	* @apiVersion 1.0.0
	* @apiDescription  图片上传
	
	* @apiHeader {String} Authorization 用户授权token
	* @apiHeaderExample {json} Header-示例:
	* "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOjM2NzgsImF1ZGllbmNlIjoid2ViIiwib3BlbkFJZCI6MTM2NywiY3JlYXRlZCI6MTUzMzg3OTM2ODA0Nywicm9sZXMiOiJVU0VSIiwiZXhwIjoxNTM0NDg0MTY4fQ.Gl5L-NpuwhjuPXFuhPax8ak5c64skjDTCBC64N_QdKQ2VT-zZeceuzXB9TqaYJuhkwNYEhrV3pUx1zhMWG7Org"
	
	* @apiParam (失败返回参数：) {object}     	array 返回结果集
	* @apiParam (失败返回参数：) {string}     	array.status 返回错误码  201
	* @apiParam (失败返回参数：) {string}     	array.msg 返回错误消息
	* @apiParam (成功返回参数：) {string}     	array 返回结果集
	* @apiParam (成功返回参数：) {string}     	array.status 返回错误码 200
	* @apiParam (成功返回参数：) {string}     	array.data 返回图片地址
	* @apiSuccessExample {json} 01 成功示例
	* {"status":"200","data":"操作成功"}
	* @apiErrorExample {json} 02 失败示例
	* {"status":" 201","msg":"操作失败"}
	*/
	public function upload(){
		if(!$_FILES){
			return json(['status'=>config('my.errorCode'),'msg'=>'图片上传为空']);
		}
		$file = $this->request->file(array_keys($_FILES)[0]);
		
		$file->validate(['size'=>config('my.api_upload_max'),'ext'=>config('my.api_upload_ext')]);
		try{
			$info = $file->rule('uniqid')->move(config('my.api_upload_dir'));
		}catch(\Exception $e){
			return json(['status'=>config('my.errorCode'),'msg'=>$e->getMessage()]);
		}	
		if($info){
			if(config('my.qiniuyun_status')){
				//上传七牛云
				$url = \app\api\service\oss\QiniuService::uploadQiniuyun(config('my.api_upload_dir').'/'.$info->getSaveName());
				@unlink(config('my.api_upload_dir').'/'.$info->getSaveName()); //上传成功删除本地文件
			}else{
				//本地上传如果配置了域名则 解析域名到/public/uploads目录 并且返回完整图片路径
				$url = !empty(config('my.api_upload_domain')) ? config('my.api_upload_domain').'/api/'.$info->getSaveName() : ltrim(config('my.api_upload_dir'),'.').'/'.$info->getSaveName();
			}	
			$ret = ['status'=>config('my.successCode'),'data'=>$url];
		}else{
			$ret = ['status'=>config('my.errorCode'),'msg'=>'上传失败'];
		}
		
		return json($ret);
		
	}

}

